package net.wenku8.reader.view.user

import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavController
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import net.wenku8.reader.api.UserApi
import net.wenku8.reader.entity.ApiResult
import net.wenku8.reader.enums.KeyLoginPassword
import net.wenku8.reader.enums.KeyLoginRememberPassword
import net.wenku8.reader.enums.KeyLoginUsername
import net.wenku8.reader.view.common.BaseViewModel

class LoginViewModel : BaseViewModel() {

    val username = mutableStateOf("")
    val password = mutableStateOf("")
    val rememberPassword = mutableStateOf(false)

    fun initData(){
        val loginUsername = MMKV.defaultMMKV().decodeString(KeyLoginUsername)
        val loginPassword = MMKV.defaultMMKV().decodeString(KeyLoginPassword)
        val loginRememberPassword = MMKV.defaultMMKV().decodeBool(KeyLoginRememberPassword, false)
        if (loginUsername != null && loginPassword != null && loginRememberPassword){
            username.value = loginUsername
            password.value = loginPassword
            rememberPassword.value = true
        }
    }

    fun onLogin(navController : NavController) {
        if (rememberPassword.value){
            MMKV.defaultMMKV().encode(KeyLoginUsername, username.value)
            MMKV.defaultMMKV().encode(KeyLoginPassword, password.value)
            MMKV.defaultMMKV().encode(KeyLoginRememberPassword, rememberPassword.value)
        }
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = UserApi.login(username.value, password.value)
            if (ApiResult.isSuccess(apiResult)){
                withContext(Dispatchers.Main){
                    navController.popBackStack()
                }
            }else{
                showSnackbar(apiResult.message)
            }
        }
    }

}